package com.maiji.cloud.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.maiji.cloud.request.shopingmall.OrderPrintReqData;
import org.apache.commons.lang.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Express100Util {
    static Logger logger = LoggerFactory.getLogger(Express100Util.class);

    // 打印电子面单方法
    private static final String METHOD = "getPrintImg";
    //快递100授权秘钥
    public static final String KEY = "doXABRdc3850";
    // 电子面单secret
    private static final String SECRET = "85ce3c4fe8764d9a9f5158541d8fe1db";
    // 淘宝授权电子面单账号密码
    private static final String PARTNERID = "3339722833";
    private static final String PARTNERKEY = "6201609e97cfde5degi93b325649d4d81b5d60a76f1bf633339722833";
    private static final String NET = "taobao";
    //快递名称
    public static final String KUAIDI_NAME = "申通快递";
    // 快递公司编号
    public static final String KUAIDICOM = "shentong";
    // 电子面单模板ID
    private static final String TEMPID = "703cc83f6e6c488697da8181ae5e872c";
    // 生成图片内容，默认10为电子面单
    private static final String TYPE = "10";
    // 快递公司查询编号
    private static final String CUSTOMER = "3F1C6DD6501C60FB3CE1D038F4A49D4D";
    /**
     * 实时查询请求地址
     */
    private static final String SYNQUERY_URL = "http://poll.kuaidi100.com/poll/query.do";
    /**
     *  打印电子面单地址
     */
    private static final String PRINT_URL = "https://poll.kuaidi100.com/printapi/printtask.do";
    //  寄件人姓名
    private static final String SENDMANNAME = "麦麦";
    //  寄件人的手机号
    private static final String SENDMANMOBILE = "15662090119";
    //  寄件人所在完整地址
    private static final String SENDMANPRINTADDR = "泰安市泰山区天龙国际大厦A座";

    /**
     *  打印电子面单 - 封装
     * @return
     */
    public static void expressPrint (OrderPrintReqData orderPrint) {
        String expressPrintJSONStr = null;
        try {
            Double weight = Arith.divides(2, orderPrint.getSendWeight(), 1000);
            expressPrintJSONStr = Express100Util.expressPrint(orderPrint.getConsignee(),
                    orderPrint.getTel(), orderPrint.getAdr(), weight, orderPrint.getOrderNoNew());
            HashMap expressPrintResult = JSON.parseObject(expressPrintJSONStr, HashMap.class);
            Boolean result = (Boolean) expressPrintResult.get("result");
            if (BooleanUtils.isFalse(result)) {
                logger.info("Express100Util.expressPrint() ==> JSONStr ===> false = {}", expressPrintJSONStr);
                orderPrint.setPrintErrorMsg(expressPrintResult.get("message").toString());
            }
            if (BooleanUtils.isTrue(result)) {
                HashMap expressPrintData = JSON.parseObject(expressPrintResult.get("data").toString(), HashMap.class);
                orderPrint.setExpressPrintData(expressPrintData);
            }
        } catch (Exception e) {
            logger.info("Express100Util.expressPrint() ==> expressPrintJSONStr ===> Error = {}", expressPrintJSONStr);
            e.printStackTrace();
        }

    }

    /**
     *  打印电子面单
     * @param recManName  收件人姓名
     * @param recManMobile  收件人的手机号
     * @param recManPrintAddr  收件人所在完整地址
     * @param weight  物品总重量KG，double类型
     * @param orderId  订单编号
     * @return
     */
    public static String expressPrint(String recManName, String recManMobile, String recManPrintAddr, Double weight, String orderId) {
        StringBuilder param = new StringBuilder("{");
        param.append("\"type\":\"").append(TYPE).append("\"");
        param.append(",\"partnerId\":\"").append(PARTNERID).append("\"");
        param.append(",\"partnerKey\":\"").append(PARTNERKEY).append("\"");
        param.append(",\"net\":\"").append(NET).append("\"");
        param.append(",\"kuaidicom\":\"").append(KUAIDICOM).append("\"");
        param.append(",\"recManName\":\"").append(recManName).append("\"");
        param.append(",\"recManMobile\":\"").append(recManMobile).append("\"");
        param.append(",\"recManPrintAddr\":\"").append(recManPrintAddr).append("\"");
        param.append(",\"sendManName\":\"").append(SENDMANNAME).append("\"");
        param.append(",\"sendManMobile\":\"").append(SENDMANMOBILE).append("\"");
        param.append(",\"sendManPrintAddr\":\"").append(SENDMANPRINTADDR).append("\"");
        param.append(",\"count\":\"").append("1").append("\"");
        param.append(",\"weight\":\"").append(weight.toString()).append("\"");
        param.append(",\"needChild\":\"").append("0").append("\"");
        param.append(",\"orderId\":\"").append(orderId).append("\"");
        param.append(",\"tempid\":\"").append(TEMPID).append("\"");
        param.append(",\"content\":\"").append(orderId).append("\"");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        param.append(",\"printTime\":\"").append(sdf.format(new Date())).append("\"");
        param.append("}");
        Map<String, String> params = new HashMap<>();
        params.put("method", METHOD);
        params.put("key", KEY);
        String time = String.valueOf(new Date().getTime());
        params.put("t", time);
        String sign = MD5Utils.encode(param.toString() + time + KEY + SECRET).toUpperCase();
        params.put("sign", sign);
        params.put("param", param.toString());
        System.out.println(JSON.toJSONString(params));
        return post(params, PRINT_URL);
    }

    /**
     * 实时查询快递单号
     * @param com			快递公司编码
     * @param num			快递单号
     * @param phone			手机号
     * @param from			出发地城市
     * @param to			目的地城市
     * @param resultv2		开通区域解析功能：0-关闭；1-开通
     * @return
     */
    public static String expressQuery(String com, String num, String phone, String from, String to, int resultv2) {
        StringBuilder param = new StringBuilder("{");
        param.append("\"com\":\"").append(com).append("\"");
        param.append(",\"num\":\"").append(num).append("\"");
        param.append(",\"phone\":\"").append(phone).append("\"");
        param.append(",\"from\":\"").append(from).append("\"");
        param.append(",\"to\":\"").append(to).append("\"");
        if(1 == resultv2) {
            param.append(",\"resultv2\":1");
        } else {
            param.append(",\"resultv2\":0");
        }
        param.append("}");
        Map<String, String> params = new HashMap<String, String>();
        params.put("customer", CUSTOMER);
        String sign = MD5Utils.encode(param.toString() + KEY + CUSTOMER);
        params.put("sign", sign);
        params.put("param", param.toString());
        return post(params, SYNQUERY_URL);
    }

    /**
     * 发送post请求
     */
    public static String post(Map<String, String> params, String url_100) {
        StringBuffer response = new StringBuffer("");

        BufferedReader reader = null;
        try {
            StringBuilder builder = new StringBuilder();
            for (Map.Entry<String, String> param : params.entrySet()) {
                if (builder.length() > 0) {
                    builder.append('&');
                }
                builder.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                builder.append('=');
                builder.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
            }
            byte[] bytes = builder.toString().getBytes("UTF-8");

            URL url = new URL(url_100);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(bytes);

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return response.toString();
    }

    public static void main(String[] args) {
//        expressQuery("")

//        String expressPrint = expressPrint("李四", "15053766744",
//                "山东省济南市高新区财富中心B2-1018",1.00, "1234567890");
//        System.out.println(expressPrint);
//        HashMap expressPrintResult = JSON.parseObject(expressPrint, HashMap.class);
//        String returnCode = expressPrintResult.get("returnCode").toString();
//        if (! returnCode.equals("200") && ! returnCode.equals("501")) return;
//        HashMap expressPrintData = JSON.parseObject(expressPrintResult.get("data").toString(), HashMap.class);
//        List<String> imgBase64s = JSON.parseObject(expressPrintData.get("imgBase64").toString(), List.class);
//        System.out.println(imgBase64s);
//		  String expressPrint = expressPrint("张三", "15053766745",
//		  "山东省济南市高新区财富中心B2-1018", 1, 3, 7.55, "1234567890987654321");
//		  System.out.println(expressPrint);

//		  String key = "doXABRdc3850"; //贵司的授权key
//		  String customer =
//		  "3F1C6DD6501C60FB3CE1D038F4A49D4D"; //贵司的查询公司编号
//		  String com = "zhongtong";
//		  //快递公司编码
//		  String num = "773001160755651"; //快递单号
//		  String phone = ""; //手机号码后四位
//		  String from = ""; //出发地
//		  String to = ""; //目的地
//		  int resultv2 = 0; //开启行政规划解析
//		  String result = expressQuery(com, num, phone, from, to, resultv2);
//		  System.out.println(result);
//
//    	JSONObject jsonObject = JSONObject.fromObject(result);
//    	Map<String, Class> classMap = new HashMap<String, Class>();
//
//    	classMap.put("data", So.class);
//    	Test stu = (Test) JSONObject.toBean(jsonObject, Test.class, classMap);
//
//    	List<So> list = stu.getData();
//    	So so1 = new So();
//    	so1.setContext("揽收");
//    	list.add(list.size(), so1);
//    	for (So so : list) {
//    	System.out.println(so.getContext());
	 
    }

}
